<template>
  <common-page title="人员管理">
    <avue-crud ref="crud" v-model="form" class="crud-table" :option="option" :data="list" :page.sync="page"
               :search.sync="searchForm" :table-loading="loading" :header-cell-class-name="() => 'crud-table-head'"
               :cell-class-name="() => 'crud-cell'" @on-load="handleOnload()" @search-change="searchChange"
               @refresh-change="getList()" @row-update="update" @row-save="create" @row-del="handleDelete"
               @search-reset="searchChange">
      <template #searchMenu="{ size }">
        <el-button type="primary" :size="size" @click="searchChange">查 询</el-button>
        <el-button type="primary" plain :size="size" @click="resetForm">重 置</el-button>
      </template>
      <template #menu="{ row, size, type }">
        <el-button v-if="row.tenantStatus === 0" :type="type" :size="size" @click="startUser(row)">启用</el-button>
        <el-button v-else :type="type" :size="size" @click="stopUser(row)">停用</el-button>
      </template>
      <template slot="tenantStatus" slot-scope="scope">
        <el-tag v-if="scope.row.tenantStatus === 0" type="danger">已停用</el-tag>
        <el-tag v-else-if="scope.row.tenantStatus === 1" type="success">正常</el-tag>
        <el-tag v-else type="warning">未激活</el-tag>
      </template>
    </avue-crud>
  </common-page>
</template>

<script>
import { getPage, getAllDepartments, getAllRoles, getDeptPostsList,addUser,deleteOne ,startUser,stopUser,edit} from "@/api/person"
import { tableOption } from "./tableOption";

export default {
  name: "person",

  data () {
    return {
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      list: [],
      deptList: [],
      roleList: [],
      postList: [],
      choosePostList: [],
      loading: true,
      form: {},
      isShowSearch: false,
    };
  },
  computed: {
    option () {
      return tableOption.call(this);
    },
    documentHeight () {
      return this.$store.state.app.documentClientHeight;
    },
  },
  // created() {
  //   this.checkList = this.tableOption.columns.map((i) => i.prop);
  // },
  watch: {
    "form.postId" (val, oldVal) {
    console.log("🤡 ~ val:", this.postList,val, oldVal)
      if (val !== undefined ) {
          this.choosePostList = this.postList.filter((i) => i.id !== val);
      }
    },
  },
  methods: {
    handleOnload () {
      this.getList();
      this.getDeptList();
      this.getRoleList();
      this.getDeptPosts();
    },
    init () {
      this.page.currentPage = 1;
      this.page.pageSize = 10;
      this.list = [];
      this.getList();
    },
    resetForm () {
      this.$refs.crud.searchReset();
    },
    openSearch () {
      this.isShowSearch = true;
    },
    handleColumn (prop, e) {
      if (prop == "MENU") {
        this.$set(this.tableOption, "menu", !e);
      }
      this.$refs.crud.refreshTable();
    },
    /**
     * 获取部门树
     */
    getDeptList () {
      getAllDepartments({ parentId: 0 })
        .then((response) => {
          this.deptList = response.result
        })
        .catch(() => { });
    },
    async getRoleList () {
      const { result } = await getAllRoles( )
      this.roleList = result
    },
  async  getDeptPosts () {
     const {result} = await getDeptPostsList()
     this.postList = result;
      console.log("🤡 ~  this.postList:",  this.postList)

    },
    getList (option) {
      this.loading = true;
      getPage({
        pageNumber: this.page.currentPage,
        pageSize: this.page.pageSize,
        ...this.searchForm,
        ...(option || ""),
      })
        .then((response) => {
          this.list = response.result.records
          this.list.forEach(val => {
             val.namelist = val.postNameList?val.postNameList.toString():''
            	val.rolelist = val.roleName?val.roleName.toString():''
          })
          this.page.total = response.result.total;

        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    searchChange (form, done) {
      this.page.currentPage = 1;
      this.getList(form || "");
      done && done();
    },
    handleDelete (row, index) {
      this.$confirm("是否确认删除该用户?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        deleteOne(row.id)
          .then(() => {
            this.getList();
            this.$message.success("删除成功");
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    create (row, done, loading) {
      if (row.deputyPostIdList && typeof row.deputyPostIdList === "string") {
        row.deputyPostIdList = row.deputyPostIdList.split(",");
      }
      addUser(row)
        .then(() => {
          this.getList();
          done();
          this.$message.success("创建成功");
        })
        .catch(() => {
          loading();
        });
    },
    update (row, index, done, loading) {
      // if (row.deputyPostIdList && typeof row.deputyPostIdList === "string") {
      //   row.deputyPostIdList = row.deputyPostIdList.split(",");
      // }
      const data = {
        id: row.id,
        realName: row.realName,
        mobile: row.mobile,
        email: row.email,
        sex: row.sex,
        departId: row.departId,
        postId: row.postId,
        roles: row.roles,
        postIds: row.postIds,
        remark: row.remark,
      };
      // if (typeof data.postIdList === "string") {
      //   data.postIdList = data.postIdList.split(",");
      // }

      edit(data)
        .then(() => {
          this.getList();
          done();
          this.$message.success("修改成功");
        })
        .catch(() => {
          loading();
        });
    },
    stopUser (row) {
      this.$confirm("是否确认停用该用户?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        stopUser({
          userId: row.id
        })
          .then(() => {
            this.getList();

            this.$message.success("停用成功");
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    startUser (row) {
      startUser({
        userId: row.id
      }).then(() => {
        this.getList();
        this.$message.success("启用成功");
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
